package com.taint.install;

import net.bytebuddy.agent.ByteBuddyAgent;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;


public class Installer {

    public static void main(String[] args) throws UnsupportedEncodingException {

       // Installer installer=new Installer();


        if(args.length<0){
            System.out.println("args error");
            System.exit(-1);
        }
        String pid=args[0];
        //获得当前jar的位置
        String agent=getLocalJarPath();
        File agentFile =new File(agent+File.separator+"Agent.jar");
        addtoolsToClassPath();

        try{
            System.out.println("Attaching to target jvm with pid:" );
            ByteBuddyAgent.attach(agentFile.getAbsoluteFile(), pid);

            System.out.println("Attached to target jvm and loaded agent successfully");
        }catch(Exception e){
            throw new RuntimeException(e);
        }


    }


     public static void addtoolsToClassPath() {

        //File getJar = new File("/home/service/jdk1.8.0_291/lib" + Ftaiile.separator + "tools.jar");
        File getJar=new File("/Library/Java/JavaVirtualMachines/jdk1.8.0_311.jdk/Contents/Home/lib/tools.jar");
         URLClassLoader classLoaderExt = (URLClassLoader) Installer.class.getClassLoader();
        URL jarUrl = null;
        try {
            jarUrl = getJar.toURI().toURL();
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(classLoaderExt, jarUrl);
        } catch (MalformedURLException | NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }


    public static String getLocalJarPath(){
        String path = "";
        try{
            //jar 中没有目录的概念
            URL location = Installer.class.getProtectionDomain().getCodeSource().getLocation();//获得当前的URL
            File file = new File(location.getPath());//构建指向当前URL的文件描述符
            if(file.isDirectory()){//如果是目录,指向的是包所在路径，而不是文件所在路径
                path = file.getAbsolutePath();//直接返回绝对路径
            }else{//如果是文件,这个文件指定的是jar所在的路径(注意如果是作为依赖包，这个路径是jvm启动加载的jar文件名)
                path = file.getParent();//返回jar所在的父路径
            }

        }catch (Exception e){
            e.printStackTrace();

        }
        return path;
    }

}
